package com.bardsoftware.foronuvolo.server;

import com.bardsoftware.foronuvolo.client.StartDiscussionService;
import com.bardsoftware.foronuvolo.data.Discussion;
import com.bardsoftware.foronuvolo.data.DiscussionsViewItem;
import com.bardsoftware.foronuvolo.data.ForumUser;
import com.bardsoftware.foronuvolo.data.DiscussionsViewItem.FormattedText;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskHandle;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class StartDiscussionServiceImpl extends RemoteServiceServlet
implements StartDiscussionService {
    public String startDiscussion(String message) {
        return sendMessage(message);
    }

    public String sendMessage(String message) {
        if (!getThreadLocalRequest().getRequestURL().toString().startsWith(ForoNuvoloConstants.FORUM_DOMAIN)) {
            return null;
        }
        ForumUser user = com.bardsoftware.foronuvolo.server.UserService.getUser(getThreadLocalRequest());
        if (!user.canWrite()) {
            return null;
        }
        Discussion newDiscussion = new Discussion(user, message);
        newDiscussion.save();
        DiscussionsViewPage.resetDiscussionViewPageCache();
        TaskOptions options = TaskOptions.Builder.url(ForoNuvoloConstants.INDEX_PATH)
            .param("start", newDiscussion.getCreationOrder())
            .param("nonext", "true")
            .method(TaskOptions.Method.GET);
        TaskHandle add = QueueFactory.getDefaultQueue().add(options);
        return "";
    }

    public String formatPreview(String message) {
        WikiMessageFormatter formatter = new WikiMessageFormatter();
        FormattedText formatted = DiscussionsViewItem.format(message, formatter, "{0}");
        return formatted.text;
    }
}
